package com.xiaoyu.lanling.feature.profile.activity

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.user.UserSetProfileEvent
import com.xiaoyu.lanling.feature.user.data.UserInfoData
import com.xiaoyu.lanling.view.listener.BaseTextWatcher
import kotlinx.android.synthetic.main.activity_user_profile_edit_soliloquy.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class UserSoliloquyEditActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_user_profile_edit_soliloquy)
        initToolbar()

        initView()
        initBind()
        initEvent()
        initData()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_user_edit, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.save -> {
                UserInfoData.setSoliloquy(requestTag, edit_text.text.toString())
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initView() {
        title = AppContext.getString(R.string.user_profile_edit_soliloquy_title)
    }

    private fun initBind() {
        edit_text.addTextChangedListener(object : BaseTextWatcher() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                s?.let {
                    renderLengthDesc(it.length)
                }
            }
        })
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: UserSetProfileEvent) {
                if (event.isNotFromThisRequestTag(requestTag) || event.isFailed) {
                    return
                }
                finish()
            }
        })
    }

    private fun initData() {
        val soliloquy = intent.getStringExtra(Constant.IntentKey.KEY_USER_PROFILE_SOLILOQUY) ?: ""
        edit_text.setText(soliloquy)
        renderLengthDesc(soliloquy.length)
    }

    private fun renderLengthDesc(length: Int) {
        length_desc.text = "${length}/${UserInfoData.MAX_SOLILOQUY_LENGTH}"
    }
}